﻿using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
/// <summary>
/// 使物体获取播放音乐的能力
/// </summary>
public class ObtainMusic : MonoBehaviour {

#region 字段
    [SerializeField, Tooltip("获取Entity脚本")]
    private Entity entity = null;
    [Tooltip("获取自身的Audiosource")]
    public AudioSource audioSource;
    [SerializeField, Tooltip("获取最初音乐的种类")]
    private KOMusic music;//获取最初的音频
    [SerializeField, Tooltip("获取四种按钮的音效")]
    public KOMusic[] musicGather;
    [SerializeField, Tooltip("音效还是音乐")]
    private MusicOrSound ms;
    [SerializeField, Tooltip("是否开始播放")]
    private bool isPlay = true;
#endregion 
    // Use this for initialization

    public KOMusic Music
    {
        get { return music; }
        set
        {
            if (value == KOMusic.NULL)
            {
                audioSource.Stop();
            } else
            {
                if(audioSource.isPlaying == true) audioSource.Stop();
                audioSource.clip = MusicManager.Instance.music[(int)value - 1];
                audioSource.Play();
            }
        }
    }//音乐的种类
    public void ChangeClip(KOMusic kOMusic)
    {
        if (MusicManager.Instance != null)
        {
            if (ms == MusicOrSound.Music && MusicManager.Instance.IsNStopM)
                Music = kOMusic;
            else if (ms == MusicOrSound.Sound && MusicManager.Instance.IsNStopS)
                Music = kOMusic;
        }
    }//改变音乐的种类，并判断是否播放
    public void OnClike()
    {
        if (MusicManager.Instance != null)
        {
            if ((MusicManager.Instance.IsNStopS && ms == MusicOrSound.Sound) || (MusicManager.Instance.IsNStopM && ms == MusicOrSound.Music))
                audioSource.Play();
        }
    }
    public void TrunLoop(bool isLoop)
    {
        audioSource.loop = isLoop;
    }//是否循环
    void Start () {
        audioSource = GetComponent<AudioSource>();
        if (MusicManager.Instance != null)
        {
            Music = music;
            if(!isPlay)audioSource.Stop();
            if (ms == MusicOrSound.Music)
            {
                audioSource.volume = MusicManager.Instance.MusicValue;
                if (!MusicManager.Instance.IsNStopM)
                    audioSource.Stop();
            }
            else
            {
                audioSource.volume = MusicManager.Instance.SoundValue;
                if (!MusicManager.Instance.IsNStopS)
                    audioSource.Stop();
            }
            MusicManager.Instance.AddMusic(ms, audioSource);
            if (entity != null) entity.OnChangeSound += ChangeClip;
        }
    }
    private void OnDestroy()
    {
        if (MusicManager.Instance != null)
        {
            MusicManager.Instance.RemoveMusic(audioSource);
        }
    }//当物体被破坏时移除该播放器
}
